<!--
 * @Descripttion: 编辑交易规则
 * @version:
 * @Author: 穆宏宇
 * @Date: 2020-10-22 16:49:09
 * @LastEditors: 穆宏宇
 * @LastEditTime: 2020-10-29 17:44:56
-->
<template>
  <div class="introduction">
    <el-upload
      class="uploadImage"
      :action="fileUrl"
      :data="{ fileType: 15 }"
      :headers="fileHeaders"
      accept=".jpg,.jpeg,.png,.gif"
      multiple
      :file-list="fileList"
      :before-upload="loadingFn"
      :on-success="handleImgSuccess"
      :on-error="handleImgError"
    >
    </el-upload>
    <div class="edit-box" v-loading="loading">
      <quill-editor
        ref="text"
        v-model="content"
        class="myQuillEditor"
        :options="editorOption"
      />
    </div>

    <div class="btn">
      <el-button type="primary" @click="savePlatformIntroductionFn">
        保存
      </el-button>
    </div>
  </div>
</template>

<script>
import { quillEditor } from "vue-quill-editor";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import fileUpdata from "@/api/file.config";
import {
  savePlatformIntroduction,
  selectPlatformIntroduction,
} from "@/api/admin.api";
import { removeByUrls } from "@/api/common.api"
// import { Base64 } from "js-base64";
// 工具栏配置
const toolbarOptions = [
  ["bold", "italic", "underline", "strike"], // toggled buttons
  ["blockquote", "code-block"],

  [{ header: 1 }, { header: 2 }], // custom button values
  [{ list: "ordered" }, { list: "bullet" }],
  [{ script: "sub" }, { script: "super" }], // superscript/subscript
  [{ indent: "-1" }, { indent: "+1" }], // outdent/indent
  [{ direction: "rtl" }], // text direction

  [{ size: ["small", false, "large", "huge"] }], // custom dropdown
  [{ header: [1, 2, 3, 4, 5, 6, false] }],

  [{ color: [] }, { background: [] }], // dropdown with defaults from theme
  [{ font: [] }],
  [{ align: [] }],
  ["link", "image"],
  ["clean"], // remove formatting button
];
export default {
  name: "edit-trading-rules",
  components: {
    quillEditor,
  },
  data() {
    return {
      fileUrl: fileUpdata.url,
      fileHeaders: fileUpdata.headers(),
      fileList: [],
      content: "",
      id: "",
      editorOption: {
        modules: {
          toolbar: {
            container: toolbarOptions, // 工具栏
            handlers: {
              image: (value) => {
                if (value) {
                  document.querySelector(".uploadImage input").click();
                } else {
                  this.quill.format("image", false);
                }
              },
              upload: (value) => {
                if (value) {
                  alert("自定义文件上传");
                }
              },
            },
          },
        },
      },
      oldData: "",
      loading: false
    };
  },
  mounted() {
    this.init();
  },
  computed: {
    oldUrls() {
      let temp = [];
      if (this.oldData) {
        let imgReg = /<img.*?(?:>|\/>)/gi;
        let srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i;
        let arr = this.oldData.match(imgReg);
        if (arr && arr.length) {
          for (let i = 0; i < arr.length; i++) {
            let src = arr[i].match(srcReg); //获取图片地址
            if (src[1]) {
              temp.push(src[1]);
            }
          }
        }
      }
      return temp;
    },
    newUrls() {
      let temp = [];
      if (this.content) {
        let imgReg = /<img.*?(?:>|\/>)/gi;
        let srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i;
        let arr = this.content.match(imgReg);
        if (arr && arr.length) {
          for (let i = 0; i < arr.length; i++) {
            let src = arr[i].match(srcReg); //获取图片地址
            if (src[1]) {
              temp.push(src[1]);
            }
          }
        }
      }
      return temp;
    },
  },
  // beforeRouteLeave(to, from, next) {
  //   next(false)
  //   this.$confirm('您还未保存简介，确定需要离开吗?', '提示', {
  //     confirmButtonText: '确定',
  //     cancelButtonText: '取消',
  //     type: 'warning'
  //   }).then(() => {
  //     next()
  //   })
  //   .catch(() => {
  //     // 选择取消
  //   })
  // },
  methods: {
    init() {
      this.quill = this.$refs.text.quill;
      let dom = this.quill.container;
      let bodyH = document.body.clientHeight;
      dom.style.height = bodyH - 250 + "px";
      this.getDetail();
    },
    // 上传成功
    handleImgSuccess(res) {
      if (res && res.code === 0) {
        // 获取光标所在位置
        let length = this.quill.getSelection().index;
        // 插入图片 res.url为服务器返回的图片地址
        this.quill.insertEmbed(length, "image", res.data.url);
        // 调整光标到最后
        this.quill.setSelection(length + 1);
      } else {
        this.$message.error("图片插入失败");
      }
      this.fileList = []
      this.loading = false
    },
    //  上传失败
    handleImgError(err) {
      this.$message.error("图片插入失败");
      this.loading = false
    },
    // 获取老数据
    getDetail() {
      selectPlatformIntroduction().then((res) => {
        this.oldData = JSON.parse(JSON.stringify(res.content));
        this.content = res.content;
      });
    },
    // 保存
    savePlatformIntroductionFn() {
      if (!this.content) {
        return this.$message.error("请输入内容");
      }
      let data = {
        content: this.content,
      };
      savePlatformIntroduction(data).then((res) => {
        if (res === "true") {
          this.diff()
          this.oldData = JSON.parse(JSON.stringify(this.content));
          this.$message.success("保存成功！");
        } else {
          this.$message.error("保存失败！");
        }
      });
    },
    // 计算不需要了的图片
    diff(){
      let arr = this.oldUrls.filter(key=> !this.newUrls.includes(key))
      if (arr&&arr.length) {
        removeByUrls({
          urls: arr
        })
      }
    },
    loadingFn(){
      this.loading = true
    }
  },
};
</script>

<style scoped lang='scss'>
.introduction {
  .uploadImage {
    display: none;
  }
  .btn {
    margin-top: 10px;
    text-align: center;
  }
}
</style>
